package cc.shacocloud.mirage.utils.comparator;

import org.jetbrains.annotations.Nullable;

import java.util.Comparator;

/**
 * {@link Comparator} 实现 {@link Ordered} 对象，分别按顺序值升序排序，分别按优先级降序排序。
 *
 * @see Ordered
 * @see java.util.List#sort(java.util.Comparator)
 * @see java.util.Arrays#sort(Object[], java.util.Comparator)
 */
public class OrderComparator implements Comparator<Object> {
    
    /**
     * {@code OrderComparator} 的共享默认实例
     */
    public static final OrderComparator INSTANCE = new OrderComparator();
    
    @Override
    public int compare(@Nullable Object o1, @Nullable Object o2) {
        return doCompare(o1, o2);
    }
    
    private int doCompare(@Nullable Object o1, @Nullable Object o2) {
        boolean p1 = (o1 instanceof Ordered);
        boolean p2 = (o2 instanceof Ordered);
        if (p1 && !p2) {
            return -1;
        } else if (p2 && !p1) {
            return 1;
        }
        
        int i1 = getOrder(o1);
        int i2 = getOrder(o2);
        return Integer.compare(i1, i2);
    }
    
    /**
     * 确定给定对象的值
     *
     * @param obj 要检查的对象
     * @return 值，或 {@code Ordered.LOWEST_PRECEDENCE}
     */
    public int getOrder(@Nullable Object obj) {
        return getOrder(obj, Ordered.LOWEST_PRECEDENCE);
    }
    
    /**
     * 确定给定对象的值
     *
     * @param obj          要检查的对象
     * @param defaultValue 默认值
     * @return 值，或 {@code Ordered.LOWEST_PRECEDENCE}
     */
    public int getOrder(@Nullable Object obj, Integer defaultValue) {
        if (obj != null) {
            Integer order = findOrder(obj);
            if (order != null) {
                return order;
            }
        }
        return defaultValue;
    }
    
    /**
     * 查找给定对象指示的值。
     *
     * @param obj 要检查的对象
     * @return 订单值，如果未找到，则为 {@code null}
     */
    @Nullable
    protected Integer findOrder(Object obj) {
        return (obj instanceof Ordered ? ((Ordered) obj).getOrder() : null);
    }
    
}
